"""
数据管理器

统一的数据访问和管理接口，协调各种数据源和适配器。
"""

from typing import Dict, List, Any, Optional, Union, Type, TYPE_CHECKING
from datetime import datetime, timedelta, date
import asyncio
import json
import hashlib
from abc import ABC, abstractmethod

from ..config.settings import settings

if TYPE_CHECKING:
    from .data_adapters import DataAdapter
    from .data_cache import DataCache
    from .data_quality import DataQualityChecker
    from .data_pipeline import DataPipeline


class DataManager:
    """
    数据管理器
    
    提供统一的数据访问接口，管理多个数据源和适配器。
    """
    
    def __init__(self):
        """初始化数据管理器"""
        self._adapters: Dict[str, 'DataAdapter'] = {}
        self._cache: Optional['DataCache'] = None
        self._quality_checker: Optional['DataQualityChecker'] = None
        self._pipeline: Optional['DataPipeline'] = None
        self._initialized = False
    
    async def initialize(self) -> None:
        """
        初始化数据管理器
        
        加载配置，初始化各个组件。
        """
        if self._initialized:
            return
        
        # 初始化缓存
        from .data_cache import DataCache
        self._cache = DataCache()
        await self._cache.initialize()
        
        # 初始化数据质量检查器
        from .data_quality import DataQualityChecker
        self._quality_checker = DataQualityChecker()
        
        # 初始化数据管道
        from .data_pipeline import DataPipeline
        self._pipeline = DataPipeline("default_pipeline", "Default Data Pipeline")
        
        # 注册默认适配器
        await self._register_default_adapters()
        
        self._initialized = True
    
    async def _register_default_adapters(self) -> None:
        """注册默认的数据适配器"""
        from .data_adapters import (
            TushareAdapter,
            WindAdapter,
            DatabaseAdapter,
            AKShareAdapter
        )
        
        # 注册AKShare适配器（免费，优先使用）
        try:
            akshare_adapter = AKShareAdapter()
            await self.register_adapter("akshare", akshare_adapter)
        except Exception as e:
            print(f"Failed to register AKShare adapter: {e}")
        
        # 注册Tushare适配器
        if hasattr(settings, 'TUSHARE_TOKEN') and settings.TUSHARE_TOKEN:
            try:
                tushare_adapter = TushareAdapter(settings.TUSHARE_TOKEN)
                await self.register_adapter("tushare", tushare_adapter)
            except Exception as e:
                print(f"Failed to register Tushare adapter: {e}")
        
        # 注册Wind适配器
        if (hasattr(settings, 'WIND_USERNAME') and hasattr(settings, 'WIND_PASSWORD') and
            settings.WIND_USERNAME and settings.WIND_PASSWORD):
            try:
                wind_adapter = WindAdapter(
                    username=settings.WIND_USERNAME,
                    password=settings.WIND_PASSWORD
                )
                await self.register_adapter("wind", wind_adapter)
            except Exception as e:
                print(f"Failed to register Wind adapter: {e}")
        
        # 注册数据库适配器
        try:
            database_adapter = DatabaseAdapter()
            await self.register_adapter("database", database_adapter)
        except Exception as e:
            print(f"Failed to register Database adapter: {e}")
    
    async def register_adapter(self, name: str, adapter: 'DataAdapter') -> None:
        """
        注册数据适配器
        
        Args:
            name: 适配器名称
            adapter: 数据适配器实例
        """
        await adapter.initialize()
        self._adapters[name] = adapter
    
    async def get_market_data(
        self,
        symbols: Union[str, List[str]],
        start_date: datetime,
        end_date: datetime,
        fields: Optional[List[str]] = None,
        source: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        获取市场数据
        
        Args:
            symbols: 股票代码或代码列表
            start_date: 开始日期
            end_date: 结束日期
            fields: 数据字段列表
            source: 指定数据源
            
        Returns:
            市场数据字典
        """
        if not self._initialized:
            await self.initialize()
        
        # 标准化输入
        if isinstance(symbols, str):
            symbols = [symbols]
        
        if fields is None:
            fields = ["open", "high", "low", "close", "volume"]
        
        # 构建缓存键
        cache_key = self._build_cache_key(
            "market_data", symbols, start_date, end_date, fields, source
        )
        
        # 尝试从缓存获取
        if self._cache:
            cached_data = await self._cache.get(cache_key)
            if cached_data:
                return cached_data
        
        # 选择数据源
        adapter = self._select_adapter(source, "market_data")
        if not adapter:
            raise ValueError(f"No suitable adapter found for market data")
        
        # 获取数据
        data = await adapter.get_market_data(symbols, start_date, end_date, fields)
        
        # 数据质量检查
        if self._quality_checker:
            data = await self._quality_checker.validate_market_data(data)
        
        # 缓存数据
        if self._cache:
            await self._cache.set(cache_key, data, ttl=timedelta(hours=1))
        
        return data
    
    async def get_fundamental_data(
        self,
        symbols: Union[str, List[str]],
        metrics: List[str],
        period: str = "quarterly",
        source: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        获取基本面数据
        
        Args:
            symbols: 股票代码或代码列表
            metrics: 财务指标列表
            period: 报告期间（quarterly/annual）
            source: 指定数据源
            
        Returns:
            基本面数据字典
        """
        if not self._initialized:
            await self.initialize()
        
        if isinstance(symbols, str):
            symbols = [symbols]
        
        # 构建缓存键
        cache_key = self._build_cache_key(
            "fundamental_data", symbols, metrics, period, source
        )
        
        # 尝试从缓存获取
        if self._cache:
            cached_data = await self._cache.get(cache_key)
            if cached_data:
                return cached_data
        
        # 选择数据源
        adapter = self._select_adapter(source, "fundamental_data")
        if not adapter:
            raise ValueError(f"No suitable adapter found for fundamental data")
        
        # 获取数据
        data = await adapter.get_fundamental_data(symbols, metrics, period)
        
        # 数据质量检查
        if self._quality_checker:
            data = await self._quality_checker.validate_fundamental_data(data)
        
        # 缓存数据
        if self._cache:
            await self._cache.set(cache_key, data, ttl=timedelta(hours=6))
        
        return data
    
    async def get_alternative_data(
        self,
        data_type: str,
        parameters: Dict[str, Any],
        source: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        获取另类数据
        
        Args:
            data_type: 数据类型（news/social/satellite等）
            parameters: 查询参数
            source: 指定数据源
            
        Returns:
            另类数据字典
        """
        if not self._initialized:
            await self.initialize()
        
        # 构建缓存键
        cache_key = self._build_cache_key(
            "alternative_data", data_type, parameters, source
        )
        
        # 尝试从缓存获取
        if self._cache:
            cached_data = await self._cache.get(cache_key)
            if cached_data:
                return cached_data
        
        # 选择数据源
        adapter = self._select_adapter(source, "alternative_data")
        if not adapter:
            raise ValueError(f"No suitable adapter found for alternative data")
        
        # 获取数据
        data = await adapter.get_alternative_data(data_type, parameters)
        
        # 数据质量检查
        if self._quality_checker:
            data = await self._quality_checker.validate_alternative_data(data)
        
        # 缓存数据
        if self._cache:
            await self._cache.set(cache_key, data, ttl=timedelta(minutes=30))
        
        return data
    
    async def get_real_time_data(
        self,
        symbols: Union[str, List[str]],
        fields: Optional[List[str]] = None,
        source: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        获取实时数据
        
        Args:
            symbols: 股票代码或代码列表
            fields: 数据字段列表
            source: 指定数据源
            
        Returns:
            实时数据字典
        """
        if not self._initialized:
            await self.initialize()
        
        if isinstance(symbols, str):
            symbols = [symbols]
        
        if fields is None:
            fields = ["last_price", "volume", "bid", "ask"]
        
        # 选择数据源
        adapter = self._select_adapter(source, "real_time_data")
        if not adapter:
            raise ValueError(f"No suitable adapter found for real-time data")
        
        # 获取数据（实时数据不缓存）
        data = await adapter.get_real_time_data(symbols, fields)
        
        # 数据质量检查
        if self._quality_checker:
            data = await self._quality_checker.validate_real_time_data(data)
        
        return data
    
    async def store_data(
        self,
        data: Dict[str, Any],
        data_type: str,
        metadata: Optional[Dict[str, Any]] = None
    ) -> bool:
        """
        存储数据
        
        Args:
            data: 要存储的数据
            data_type: 数据类型
            metadata: 元数据
            
        Returns:
            存储是否成功
        """
        if not self._initialized:
            await self.initialize()
        
        # 使用数据库适配器存储
        database_adapter = self._adapters.get("database")
        if not database_adapter:
            raise ValueError("Database adapter not available")
        
        return await database_adapter.store_data(data, data_type, metadata)
    
    async def run_pipeline(
        self,
        pipeline_name: str,
        parameters: Optional[Dict[str, Any]] = None
    ) -> Dict[str, Any]:
        """
        运行数据管道
        
        Args:
            pipeline_name: 管道名称
            parameters: 管道参数
            
        Returns:
            管道执行结果
        """
        if not self._initialized:
            await self.initialize()
        
        if not self._pipeline:
            raise ValueError("Data pipeline not initialized")
        
        return await self._pipeline.run(pipeline_name, parameters or {})
    
    def _select_adapter(
        self,
        source: Optional[str],
        data_type: str
    ) -> Optional['DataAdapter']:
        """
        选择合适的数据适配器
        
        Args:
            source: 指定的数据源
            data_type: 数据类型
            
        Returns:
            选中的适配器
        """
        if source and source in self._adapters:
            return self._adapters[source]
        
        # 根据数据类型选择默认适配器
        if data_type in ["market_data", "fundamental_data"]:
            # 优先选择Tushare，其次Wind
            for adapter_name in ["tushare", "wind", "database"]:
                if adapter_name in self._adapters:
                    return self._adapters[adapter_name]
        
        elif data_type == "real_time_data":
            # 实时数据优先选择Wind
            for adapter_name in ["wind", "tushare"]:
                if adapter_name in self._adapters:
                    return self._adapters[adapter_name]
        
        elif data_type == "alternative_data":
            # 另类数据可能需要专门的适配器
            return self._adapters.get("database")
        
        return None
    
    def _build_cache_key(self, *args) -> str:
        """
        构建缓存键
        
        Args:
            *args: 缓存键组成部分
            
        Returns:
            缓存键字符串
        """
        key_parts = []
        for arg in args:
            if isinstance(arg, (list, tuple)):
                key_parts.append(",".join(str(x) for x in arg))
            elif isinstance(arg, datetime):
                key_parts.append(arg.strftime("%Y%m%d"))
            elif isinstance(arg, dict):
                key_parts.append(str(sorted(arg.items())))
            else:
                key_parts.append(str(arg))
        
        return ":".join(key_parts)
    
    async def get_adapter_status(self) -> Dict[str, Dict[str, Any]]:
        """
        获取所有适配器的状态
        
        Returns:
            适配器状态字典
        """
        status = {}
        for name, adapter in self._adapters.items():
            try:
                adapter_status = await adapter.get_status()
                status[name] = {
                    "status": "healthy",
                    "details": adapter_status
                }
            except Exception as e:
                status[name] = {
                    "status": "error",
                    "error": str(e)
                }
        
        return status
    
    async def close(self) -> None:
        """关闭数据管理器（标准生命周期方法）"""
        await self.cleanup()
    
    async def cleanup(self) -> None:
        """清理资源"""
        # 清理适配器
        for adapter in self._adapters.values():
            try:
                await adapter.cleanup()
            except Exception:
                pass
        
        # 清理缓存
        if self._cache:
            await self._cache.cleanup()
        
        self._initialized = False
    
    # API支持方法
    async def query_data(
        self,
        data_type: str,
        symbols: Optional[List[str]] = None,
        start_date: Optional[date] = None,
        end_date: Optional[date] = None,
        fields: Optional[List[str]] = None,
        filters: Optional[Dict[str, Any]] = None,
        limit: Optional[int] = None
    ) -> Dict[str, Any]:
        """
        通用数据查询接口
        
        Args:
            data_type: 数据类型
            symbols: 标的代码列表
            start_date: 开始日期
            end_date: 结束日期
            fields: 字段列表
            filters: 筛选条件
            limit: 记录数限制
            
        Returns:
            查询结果
        """
        if not self._initialized:
            await self.initialize()
        
        try:
            # 根据数据类型调用相应方法
            if data_type == "market_data":
                if not symbols:
                    raise ValueError("Market data requires symbols")
                
                start_dt = datetime.combine(start_date, datetime.min.time()) if start_date else datetime.now() - timedelta(days=30)
                end_dt = datetime.combine(end_date, datetime.min.time()) if end_date else datetime.now()
                
                result = await self.get_market_data(symbols, start_dt, end_dt, fields)
                
            elif data_type == "fundamental_data":
                if not symbols:
                    raise ValueError("Fundamental data requires symbols")
                
                metrics = fields or ["revenue", "net_income", "total_assets"]
                period = filters.get("period", "quarterly") if filters else "quarterly"
                
                result = await self.get_fundamental_data(symbols, metrics, period)
                
            elif data_type == "real_time_data":
                if not symbols:
                    raise ValueError("Real-time data requires symbols")
                
                result = await self.get_real_time_data(symbols, fields)
                
            elif data_type == "alternative_data":
                if not filters:
                    raise ValueError("Alternative data requires filters")
                
                alt_type = filters.get("type", "news")
                parameters = {k: v for k, v in filters.items() if k != "type"}
                
                result = await self.get_alternative_data(alt_type, parameters)
                
            else:
                # 尝试从数据库查询
                result = await self._query_from_database(
                    data_type, symbols, start_date, end_date, fields, filters, limit
                )
            
            # 应用限制
            if limit and isinstance(result.get("data"), list):
                result["data"] = result["data"][:limit]
                result["total"] = min(result.get("total", 0), limit)
            
            return result
            
        except Exception as e:
            return {
                "data": [],
                "total": 0,
                "error": str(e),
                "metadata": {"query_time": datetime.now().isoformat()}
            }
    
    async def _query_from_database(
        self,
        data_type: str,
        symbols: Optional[List[str]],
        start_date: Optional[date],
        end_date: Optional[date],
        fields: Optional[List[str]],
        filters: Optional[Dict[str, Any]],
        limit: Optional[int]
    ) -> Dict[str, Any]:
        """从数据库查询数据"""
        database_adapter = self._adapters.get("database")
        if not database_adapter:
            raise ValueError("Database adapter not available")
        
        # 构建查询参数
        query_params = {
            "data_type": data_type,
            "symbols": symbols,
            "start_date": start_date,
            "end_date": end_date,
            "fields": fields,
            "filters": filters or {},
            "limit": limit
        }
        
        # 执行查询
        data = await database_adapter.query_data(**query_params)
        
        return {
            "data": data if isinstance(data, list) else [data] if data else [],
            "total": len(data) if isinstance(data, list) else (1 if data else 0),
            "metadata": {"source": "database", "query_time": datetime.now().isoformat()}
        }
    
    async def upload_data(
        self,
        data_type: str,
        source: str,
        content: bytes,
        filename: str,
        metadata: Optional[Dict[str, Any]] = None,
        overwrite: bool = False
    ) -> Dict[str, Any]:
        """
        上传数据
        
        Args:
            data_type: 数据类型
            source: 数据源
            content: 文件内容
            filename: 文件名
            metadata: 元数据
            overwrite: 是否覆盖
            
        Returns:
            上传结果
        """
        if not self._initialized:
            await self.initialize()
        
        try:
            # 解析文件内容
            if filename.endswith('.csv'):
                import pandas as pd
                import io
                df = pd.read_csv(io.BytesIO(content))
                data = df.to_dict('records')
            elif filename.endswith('.json'):
                data = json.loads(content.decode('utf-8'))
            else:
                raise ValueError(f"Unsupported file format: {filename}")
            
            # 生成上传ID
            upload_id = hashlib.md5(f"{data_type}_{source}_{filename}_{datetime.now()}".encode()).hexdigest()
            
            # 存储数据
            success = await self.store_data(
                {"records": data, "upload_id": upload_id},
                data_type,
                {
                    "source": source,
                    "filename": filename,
                    "upload_time": datetime.now().isoformat(),
                    **(metadata or {})
                }
            )
            
            if success:
                return {
                    "upload_id": upload_id,
                    "records_processed": len(data) if isinstance(data, list) else 1,
                    "records_inserted": len(data) if isinstance(data, list) else 1,
                    "records_updated": 0,
                    "errors": []
                }
            else:
                raise ValueError("Failed to store data")
                
        except Exception as e:
            return {
                "upload_id": None,
                "records_processed": 0,
                "records_inserted": 0,
                "records_updated": 0,
                "errors": [str(e)]
            }
    
    async def list_data_sources(
        self,
        data_type: Optional[str] = None,
        status: Optional[str] = None
    ) -> List[Dict[str, Any]]:
        """
        列出数据源
        
        Args:
            data_type: 数据类型筛选
            status: 状态筛选
            
        Returns:
            数据源列表
        """
        if not self._initialized:
            await self.initialize()
        
        sources = []
        adapter_status = await self.get_adapter_status()
        
        for name, adapter in self._adapters.items():
            try:
                # 获取适配器支持的数据类型
                supported_types = getattr(adapter, 'supported_data_types', ['market_data', 'fundamental_data'])
                
                # 应用筛选
                if data_type and data_type not in supported_types:
                    continue
                
                adapter_info = adapter_status.get(name, {})
                source_status = "healthy" if adapter_info.get("status") == "healthy" else "error"
                
                if status and status != source_status:
                    continue
                
                source_info = {
                    "source_id": name,
                    "name": name.title(),
                    "description": f"{name.title()} data adapter",
                    "data_types": supported_types,
                    "status": source_status,
                    "last_update": datetime.now(),
                    "update_frequency": "real-time" if name in ["wind"] else "daily",
                    "quality_score": 0.9 if source_status == "healthy" else 0.0,
                    "metadata": adapter_info.get("details", {})
                }
                sources.append(source_info)
                
            except Exception as e:
                print(f"Error getting info for adapter {name}: {e}")
        
        return sources
    
    async def get_data_source(self, source_id: str) -> Optional[Dict[str, Any]]:
        """
        获取数据源详情
        
        Args:
            source_id: 数据源ID
            
        Returns:
            数据源信息
        """
        sources = await self.list_data_sources()
        for source in sources:
            if source["source_id"] == source_id:
                return source
        return None
    
    async def get_data_statistics(
        self,
        data_type: str,
        start_date: Optional[date] = None,
        end_date: Optional[date] = None
    ) -> Dict[str, Any]:
        """
        获取数据统计信息
        
        Args:
            data_type: 数据类型
            start_date: 开始日期
            end_date: 结束日期
            
        Returns:
            统计信息
        """
        if not self._initialized:
            await self.initialize()
        
        try:
            # 从数据库获取统计信息
            database_adapter = self._adapters.get("database")
            if database_adapter:
                stats = await database_adapter.get_statistics(data_type, start_date, end_date)
                return stats
            
            # 默认统计信息
            return {
                "record_count": 0,
                "date_range": {"start": start_date, "end": end_date},
                "field_statistics": {},
                "update_frequency": {"daily": 0, "weekly": 0, "monthly": 0},
                "quality_metrics": {"completeness": 0.0, "accuracy": 0.0, "timeliness": 0.0}
            }
            
        except Exception as e:
            return {
                "record_count": 0,
                "date_range": {"start": start_date, "end": end_date},
                "field_statistics": {},
                "update_frequency": {"daily": 0, "weekly": 0, "monthly": 0},
                "quality_metrics": {"completeness": 0.0, "accuracy": 0.0, "timeliness": 0.0},
                "error": str(e)
            }
    
    async def get_available_data_types(self) -> List[Dict[str, Any]]:
        """
        获取可用的数据类型
        
        Returns:
            数据类型列表
        """
        if not self._initialized:
            await self.initialize()
        
        data_types = [
            {
                "type": "market_data",
                "name": "市场数据",
                "description": "股票、期货等金融产品的价格和交易数据",
                "fields": ["open", "high", "low", "close", "volume", "amount"],
                "sources": list(self._adapters.keys()),
                "update_frequency": "实时/日频",
                "retention_period": "永久"
            },
            {
                "type": "fundamental_data",
                "name": "基本面数据",
                "description": "公司财务报表和基本面指标数据",
                "fields": ["revenue", "net_income", "total_assets", "pe_ratio", "pb_ratio"],
                "sources": [name for name in self._adapters.keys() if name != "wind"],
                "update_frequency": "季度/年度",
                "retention_period": "永久"
            },
            {
                "type": "real_time_data",
                "name": "实时数据",
                "description": "实时价格、成交量等市场数据",
                "fields": ["last_price", "volume", "bid", "ask", "bid_size", "ask_size"],
                "sources": [name for name in self._adapters.keys() if name in ["wind", "akshare"]],
                "update_frequency": "实时",
                "retention_period": "1年"
            },
            {
                "type": "alternative_data",
                "name": "另类数据",
                "description": "新闻、社交媒体、卫星图像等另类数据",
                "fields": ["content", "sentiment", "source", "timestamp"],
                "sources": ["akshare", "database"],
                "update_frequency": "实时/日频",
                "retention_period": "2年"
            }
        ]
        
        return data_types
    
    async def refresh_data(
        self,
        data_type: str,
        source: Optional[str] = None,
        force: bool = False
    ) -> Dict[str, Any]:
        """
        刷新数据
        
        Args:
            data_type: 数据类型
            source: 指定数据源
            force: 强制刷新
            
        Returns:
            刷新结果
        """
        if not self._initialized:
            await self.initialize()
        
        start_time = datetime.now()
        
        try:
            # 选择适配器
            adapter = self._select_adapter(source, data_type)
            if not adapter:
                raise ValueError(f"No suitable adapter found for {data_type}")
            
            # 执行刷新
            if hasattr(adapter, 'refresh_data'):
                result = await adapter.refresh_data(data_type, force)
            else:
                # 默认刷新逻辑：清除缓存
                if self._cache:
                    cache_pattern = f"{data_type}:*"
                    await self._cache.delete_pattern(cache_pattern)
                result = {"records_updated": 0, "status": "cache_cleared"}
            
            duration = (datetime.now() - start_time).total_seconds()
            
            return {
                "records_updated": result.get("records_updated", 0),
                "last_update": datetime.now(),
                "duration": duration,
                "status": result.get("status", "success")
            }
            
        except Exception as e:
            duration = (datetime.now() - start_time).total_seconds()
            return {
                "records_updated": 0,
                "last_update": datetime.now(),
                "duration": duration,
                "status": "error",
                "error": str(e)
            }
    
    async def get_health_status(self) -> Dict[str, Any]:
        """
        获取健康状态
        
        Returns:
            健康状态信息
        """
        if not self._initialized:
            await self.initialize()
        
        try:
            # 获取适配器状态
            adapter_status = await self.get_adapter_status()
            
            # 获取缓存状态
            cache_status = {}
            if self._cache:
                try:
                    cache_info = await self._cache.get_info()
                    cache_status = {
                        "status": "healthy",
                        "details": cache_info
                    }
                except Exception as e:
                    cache_status = {
                        "status": "error",
                        "error": str(e)
                    }
            
            # 获取数据库状态
            database_status = {}
            database_adapter = self._adapters.get("database")
            if database_adapter:
                try:
                    db_status = await database_adapter.get_status()
                    database_status = {
                        "status": "healthy",
                        "details": db_status
                    }
                except Exception as e:
                    database_status = {
                        "status": "error",
                        "error": str(e)
                    }
            
            # 计算整体状态
            all_healthy = (
                all(status.get("status") == "healthy" for status in adapter_status.values()) and
                cache_status.get("status") == "healthy" and
                database_status.get("status") == "healthy"
            )
            
            overall_status = "healthy" if all_healthy else "degraded"
            
            # 收集问题和建议
            issues = []
            recommendations = []
            
            for name, status in adapter_status.items():
                if status.get("status") != "healthy":
                    issues.append(f"Adapter {name} is not healthy: {status.get('error', 'Unknown error')}")
                    recommendations.append(f"Check {name} adapter configuration and connectivity")
            
            if cache_status.get("status") != "healthy":
                issues.append(f"Cache is not healthy: {cache_status.get('error', 'Unknown error')}")
                recommendations.append("Check Redis connectivity and configuration")
            
            if database_status.get("status") != "healthy":
                issues.append(f"Database is not healthy: {database_status.get('error', 'Unknown error')}")
                recommendations.append("Check database connectivity and configuration")
            
            return {
                "status": overall_status,
                "data_sources": adapter_status,
                "cache_status": cache_status,
                "database_status": database_status,
                "last_check": datetime.now(),
                "issues": issues,
                "recommendations": recommendations
            }
            
        except Exception as e:
            return {
                "status": "error",
                "data_sources": {},
                "cache_status": {},
                "database_status": {},
                "last_check": datetime.now(),
                "issues": [f"Health check failed: {str(e)}"],
                "recommendations": ["Check system configuration and restart services"]
            }